﻿using System;
using System.IO.Packaging;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using WpfApp.Models.attribute;
using System.ComponentModel;
using System.Collections.Generic;
using System.Windows.Input;
/*Install - Package Newtonsoft.Json
Install-Package HtmlAgilityPack*/

namespace WpfApp.Models
{
    [Description("只返回翻译")]
    internal class SimpleTrans
    {
        private static readonly string appKey = "1112e236a2d45bf8"; // 有道应用ID
        private static readonly string appSecret = "BlgxjT3OIrn1aTplvzbz6bTfDF6M0Ky2"; // 有道应用密钥
        private static readonly string apiUrl = "https://openapi.youdao.com/api"; // 有道API的URL

        [MethodComment("使用示例", "string translatedText = await SimpleTrans.Translate(textToTranslate, \"en\", \"zh-CHS\")", "注意await，这是异步的")]
        public static async Task<string> Translate(string q, string from, string to)
        {
            string salt = Guid.NewGuid().ToString(); // 生成随机的UUID作为salt
            string curtime = ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString(); // 当前UTC时间的时间戳
            string input = GetInputString(q); // 计算input
            string signStr = appKey + input + salt + curtime + appSecret; // 拼接字符串，用于生成签名
            string sign = ComputeSha256Hash(signStr); // 生成SHA-256签名

            // 构建请求参数
            var parameters = new StringBuilder();
            parameters.AppendFormat("q={0}", Uri.EscapeDataString(Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(q))));
            parameters.AppendFormat("&from={0}", Uri.EscapeDataString(from));
            parameters.AppendFormat("&to={0}", Uri.EscapeDataString(to));
            parameters.AppendFormat("&appKey={0}", appKey);
            parameters.AppendFormat("&salt={0}", salt);
            parameters.AppendFormat("&sign={0}", sign);
            parameters.AppendFormat("&signType=v3");
            parameters.AppendFormat("&curtime={0}", curtime);

            using (var client = new HttpClient())
            {
                // 发送HTTP GET请求
                var response = await client.GetStringAsync(apiUrl + "?" + parameters.ToString());
                return ParseTranslation(response); // 返回API返回的结果
            }
        }
        private static string ParseTranslation(string response)
        {
            JObject jsonResponse = JObject.Parse(response);
            if (jsonResponse["errorCode"].ToString() == "0")
            {
                JArray translationArray = (JArray)jsonResponse["translation"];
                return translationArray[0].ToString();
            }
            else
            {
                return "翻译失败，错误代码：" + jsonResponse["errorCode"];
            }
        }
        // 计算SHA-256哈希值
        private static string ComputeSha256Hash(string rawData)
        {
            using (SHA256 sha256Hash = SHA256.Create())
            {
                byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    builder.Append(bytes[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }

        // 计算input字符串
        private static string GetInputString(string q)
        {
            if (q.Length > 20)
            {
                return q.Substring(0, 10) + q.Length + q.Substring(q.Length - 10);
            }
            else
            {
                return q;
            }
        }
    }

    [Description("返回词性和翻译")]
    internal class ProTrans
    {
        public Crawler crawler;
        public ProTrans() { crawler = new Crawler(); }
        public static async Task<Dictionary<string, string>> GetProTrans(string keyword)
        {
            try
            {
                Crawler.ClearData();

                string url = $"https://m.youdao.com/result?word={keyword}&lang=en";
                await Crawler.ExtractDefinitions(url);
                Dictionary<string, string> getmeaning = new Dictionary<string, string>(Crawler.definitionsWithUrls);
                Dictionary<string, string> ProcessMeaning = new Dictionary<string, string>();
                foreach (var item in getmeaning)
                {
                    var newval = item.Value.Replace("&lt;", "<").Replace("&gt;", ">");
                    ProcessMeaning.Add(item.Key, newval);
                }

                return ProcessMeaning;
            }
            catch (Exception ex)
            {
                // Log the exception or handle it as needed
                Console.WriteLine($"An error occurred: {ex.Message}");
                return new Dictionary<string, string>();
            }
        }

    }
}
